package cn.slahser.server;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

import cn.slahser.model.Message;
import cn.slahser.tools.ServerConfig;

/***
 * 用于通知更新的server 本server用户得到所有的在线用户
 * 
 * @author Slahser
 * 
 */
public class ActionServer extends Thread {
	private Socket socket = null;
	// 登陆成功那么链接到这个端口等待通知
	private static ServerSocket server = null;
	private static boolean b = true;
	public static HashMap<String, ObjectOutputStream> UserPool = new HashMap<String, ObjectOutputStream>();

	public void run() {
		try {
			ObjectInputStream oin = new ObjectInputStream(
					socket.getInputStream());
			ObjectOutputStream oout = new ObjectOutputStream(
					socket.getOutputStream());
			// 登陆上来即过来接受通知
			while (true) {
				Message m = (Message) oin.readObject();
				UserPool.put(m.getValue().get("userid").toString(), oout);
			}
		} catch (Exception e) {
			try {
				socket.close();
			} catch (Exception e1) {
			}
		}
	}

	public static void openServer() throws Exception {
		try {
			server = new ServerSocket(Integer.parseInt(ServerConfig
					.getValue("action_server_port")));
			while (b) {
				new ActionServer(server.accept()).start();
			}

		} catch (Exception ex) {
			ex.printStackTrace();
			try {
				server.close();
			} catch (Exception e) {
			}
			throw ex;
		}
	}

	public static void closeServer() throws Exception {
		try {
			b = false;
			server.close();
		} catch (Exception ex) {
			throw ex;
		}
	}

	public ActionServer(Socket socket) {
		this.socket = socket;
	}

}
